package com.oyz;

public class MyQueue {

    private String[] data = new String[10];
    // 下一条要存储的记录下标
    private int putIndex = 0;
    // 下一条要获取的元素下标
    private int getIndex = 0;
    // data中的元素个数
    private int size = 0;
    public synchronized void put(String element){
        if(size==data.length){
            try {
                // 等待
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 唤醒消费者线程,因为这是对象锁，锁的是整个对象
        notify();
        data[putIndex] = element;
        ++size;
        ++putIndex;
        if(putIndex == data.length) putIndex = 0;
    }

    public synchronized String get(){
        if(size==0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String result = data[getIndex];
        ++getIndex;
        if(getIndex == data.length) getIndex = 0;
        --size;
        // 唤醒生产者线程
        notify();
        return result;
    }


}
